<?php

namespace app\admin\controller\business;

use app\common\controller\Backend;


class Highsea extends Backend
{

  // 当前对象模型
  protected $model = null;

  public function _initialize()
  {
    parent::_initialize();
    $this->BusinessModel = model('Business.Business');
    $this->AdminModel = model('Admin');
    $this->ReceiveModel = model('Business.Receive');
    $this->SourceModel = model('Business.Source');
  }


  public function index()
  {
    if ($this->request->isAjax()) {

      list($where, $sort, $order, $offset, $limit) = $this->buildparams();
      // $adminid  = $this->auth->id;//管理员id
      if (array_key_exists('id', $where)) {
        $where['business.id'] = $where['id'];
        unset($where['id']);
      }

      $total = $this->BusinessModel
        ->alias('business')
        ->where('adminid', null)
        ->where($where)
        ->with('source')
        ->order($sort, $order)
        ->count();

      $list = $this->BusinessModel
        ->alias('business')
        ->where('adminid', null)
        ->where($where)
        ->with('source')
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->select();

        //！！！（删除下面的）
      $sql = $this->BusinessModel
        ->alias('business')
        ->where('adminid', null)
        ->where($where)
        ->with('source')
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->fetchSql()  // 添加 fetchSql() 方法
        ->select();



      // $result = array("total" => $total, "rows" => $list);
      // $result = array("total" => $total, "rows" => $list, "where" => $this->buildparams());
      $result = array("total" => $total, "rows" => $list);
      // $this->assign('productTypes', $result);

      return json($result);
    }
    return $this->view->fetch();
  }


  //申请（apply）和 分配（allot）
  public function apply()
  {
    // $params = $this->request->post("row/a", [], 'trim');
    $param = $this->request->param();

    if ($this->request->isPOST()) {
      // $params = $this->request->post();
      $adminid = $param['row']['adminid'];
      $status = $param['status']; //apply（申请）、allot（分配）
      $busids = explode(",",  $param['ids']);
      $admin_id  = $this->auth->id;//管理员id
      // $this->assignconfig('adminid',$adminid);
      // echo '<script>console.log('.$adminid.');</script>';


      $businessinfo = $this->BusinessModel->whereIn('id', $busids)->select();
      if (!$businessinfo) {
        $this->error('某用户不存在');
      }

      $admininfo = $this->AdminModel->find($adminid);
      if (!$admininfo) {
        $this->error('分配人员不存在');
      }

      // 开始事务
      $this->BusinessModel->startTrans();
      $this->ReceiveModel->startTrans();

      $businessStatus = $this->BusinessModel->whereIn('id', $busids)->update(['adminid' => $adminid]);

      if ($businessStatus == false) {
        $this->error($this->BusinessModel->geError());
      }

      $ReceiveData = [
        'applyid' => $adminid,
        'status' => $status,
        'busid' => ''
      ];

      // 校验器
      foreach ($busids as $key => $value) {
        $ReceiveData['busid'] = $value;
        $receiveStatus = $this->ReceiveModel->save($ReceiveData);
        if ($receiveStatus == false) {
          $this->BusinessModel->rollback();
          $this->error($this->ReceiveModel->geError());
        }
      }

      if ($receiveStatus == false || $businessStatus == false) {
        $this->BusinessModel->rollback();
        $this->ReceiveModel->rollback();
        $this->error('操作失败');
      } else {
        $this->BusinessModel->commit();
        $this->ReceiveModel->commit();
        $this->success('操作成功');
      }
    } else {
      $list = $this->BusinessModel
        ->whereIn('id',  $param['ids'])
        //同 ->where('id', 'in', $param['ids'])
        ->select();

      $adminlist = $this->AdminModel->field('id, nickname')->select();

      // return json($list);
      $this->assign('row', [
        'adminlist' => $adminlist,
        'buslist' => $list,
        'status' => $param['status'] == 'apply' ? true : false
      ]);
    }
    return $this->view->fetch();
  }


  //客户来源列表
  public function source()
  {

    $sourcelist = $this->SourceModel->select();
    // list($where, $sort, $order, $offset, $limit) = $this->buildparams();
    $list = [];
    foreach ($sourcelist as $key => $value) {
      $list[] = $value['name'];
    }
    return $list;
    // $this->success('', null, $sourcelist);
  }


  // 删除
  public function del($ids = null)
  {
    $row = $this->BusinessModel->all($ids);

    if (!$row) {
      $this->error('客户不存在');
    }

    $result = $this->BusinessModel->destroy($ids);

    if (!$result) {
      $this->error($this->BusinessModel->getError());
    }

    $this->success();
  }
}
